"""
数据模型定义
"""
from pydantic import BaseModel
from typing import Optional

class NetConfig(BaseModel):
    """网络连接配置"""
    mode: str  # client 或 server
    protocol: str  # tcp 或 udp
    host: str
    port: int

class TCPConfig(BaseModel):
    """TCP连接配置 (兼容旧版本)"""
    mode: str  # client 或 server
    protocol: str  # tcp 或 udp
    host: str
    port: int

class SerialConfig(BaseModel):
    """串口配置"""
    port: str
    baud_rate: int
    data_bits: int
    stop_bits: float
    parity: str
    flow_control: str

class SendDataRequest(BaseModel):
    """发送数据请求"""
    data: str
    format: str = "text"  # text 或 hex
    
    class Config:
        # 验证数据不能为空
        validate_assignment = True
        
    def __init__(self, **data):
        # 确保 data 不为 None
        if data.get('data') is None:
            data['data'] = ''
        super().__init__(**data)

class ConnectionStats(BaseModel):
    """连接统计信息"""
    send_bytes: int = 0
    receive_bytes: int = 0
    send_count: int = 0
    receive_count: int = 0
    error_count: int = 0

class NetConnectionInfo(BaseModel):
    """网络连接信息"""
    connection_id: str
    config: NetConfig
    connected: bool
    stats: ConnectionStats

class TCPConnectionInfo(BaseModel):
    """TCP连接信息 (兼容旧版本)"""
    connection_id: str
    config: TCPConfig
    connected: bool
    stats: ConnectionStats

class SerialConnectionInfo(BaseModel):
    """串口连接信息"""
    port: str
    config: SerialConfig
    connected: bool
    stats: ConnectionStats

class SerialPort(BaseModel):
    """串口设备信息"""
    device: str
    description: str

class APIResponse(BaseModel):
    """标准API响应"""
    success: bool
    message: str
    data: Optional[dict] = None
    connection_id: Optional[str] = None  # 添加connection_id字段兼容性
    
    class Config:
        extra = "allow"  # 允许额外字段

class PortConfigRequest(BaseModel):
    """端口配置请求"""
    port: int
    
    class Config:
        schema_extra = {
            "example": {
                "port": 10001
            }
        }

class PortConfigResponse(BaseModel):
    """端口配置响应"""
    current_port: int
    host: str